package com.knightboy.smartshoes.fragment;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.knightboy.smartshoes.R;
import com.knightboy.smartshoes.activity.MainActivity;
import com.knightboy.smartshoes.core.LocationHelper;
import com.knightboy.smartshoes.core.SenserData;
import com.knightboy.smartshoes.outerNavigation.MakeUrl;
import com.knightboy.smartshoes.outerNavigation.OuterLocationService;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by 29288 on 2015/9/17.
 */
public class NaviFragment extends Fragment implements View.OnClickListener {
    EditText outDestination_et,inDestination_et;
    LinearLayout startOutNavi;
    TextView startInNavi, set_Tv;
    //室内导航出发地目的地
    private char fromChar = 'A';
    private char toChar;
    //室外导航目的地
    private String destinationStr;
    //上下文
    private Context context;

    //室内导航设置弹出框
    private AlertDialog selfdialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.fragment_navi,container,false);
        context = this.getActivity();
        //获得控件
        outDestination_et = (EditText)rootview.findViewById(R.id.outNavi_et);
        inDestination_et = (EditText)rootview.findViewById(R.id.inNavi_et);
        startOutNavi = (LinearLayout)rootview.findViewById(R.id.outNavi_ll);
        startInNavi = (TextView)rootview.findViewById(R.id.inNavi_tv);
        set_Tv = (TextView)rootview.findViewById(R.id.naviSet_tv);
        //绑定监听器
        startInNavi.setOnClickListener(this);
        startOutNavi.setOnClickListener(this);
        set_Tv.setOnClickListener(this);
        //设置处理结果的handler
        SenserData.setInnerHandler(mHandler);

        return rootview;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.inNavi_tv:
                startInNavi();
                break;
            case R.id.outNavi_ll:
                startOtNavi();
                break;
            case R.id.naviSet_tv:
                popSetWindow();
                break;
        }
    }

    /**
     * 开始室内导航
     */
    private void startInNavi(){
        String toStr = inDestination_et.getText().toString();
        if(toStr.length() != 1){
            Toast.makeText(context,"输入有误",Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(context,"开始导航",Toast.LENGTH_SHORT).show();
        inDestination_et.setText(null);
        toChar = toStr.charAt(0);
        //开始导航查询路径
        LocationHelper.getPath(fromChar, toChar);
        //设置室内导航标志
        SenserData.setIsNavi(true);;
    }

    /**
     * 开始室外导航
     */
    private void startOtNavi(){
        OuterLocationService.setmHandler(mHandler);
        //获取输入框的目的地
        destinationStr = outDestination_et.getText().toString();
        if(destinationStr.length() == 0){
            Toast.makeText(context,"输入有误",Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(context,"开始导航",Toast.LENGTH_SHORT).show();
        //开始室外导航.如果不存在室外导航服务，则开启服务
        if(!hasServiceForName("com.knightboy.smartshoes.outerNavigation.OuterLocationService")){
            //设置目的地
            MakeUrl.setDesString(destinationStr);
            //启动service
            Intent intent = new Intent(context, OuterLocationService.class);
            context.startService(intent);
        }
    }

    /**
     * 接收转向信息的Handler类
     */
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //室内导航
            if(msg.arg1 == 0){
                String mDirection = "";
                switch (LocationHelper.direction){
                    case 0:
                        mDirection = "到达";
                        break;
                    case 1:
                        mDirection = "右转";
                        break;
                    case 2:
                        mDirection = "左转";
                        break;
                    case 3:
                        mDirection = "后转";
                        break;
                    case 4:
                        mDirection = "直走";
                        break;
                }
                String str = "已到达" + LocationHelper.toPlace +"点." + "转向信息:" + mDirection;
                MainActivity.sendMessage(LocationHelper.direction);
                Toast.makeText(context,str,Toast.LENGTH_SHORT).show();

                //创建定时器,2秒后结束震动
                Timer timer = new Timer();
                //创建定时任务
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        MainActivity.sendMessage(0);
                        //导航结束
                        if(LocationHelper.toPlace == LocationHelper.destination){
                            fromChar = LocationHelper.destination;
                        }else {
                            //再次导航
                            LocationHelper.getPath(LocationHelper.toPlace, LocationHelper.destination);
                            SenserData.setIsNavi(true);
                        }
                    }
                };
                //定时任务启动
                timer.schedule(task, 2000);
                //室外导航
            }else if(msg.arg1 == 1){
                String str = "转向信息:" + msg.arg2;
                MainActivity.sendMessage(msg.arg2);
                Toast.makeText(context,str,Toast.LENGTH_SHORT).show();

                //创建定时器,2秒后结束震动
                Timer timer = new Timer();
                //创建定时任务
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        MainActivity.sendMessage(0);
                    }
                };
                //定时任务启动
                timer.schedule(task, 2000);
            }
        }
    };

    //判断该服务是否存在
    private boolean hasServiceForName(String serviceName){
        //返回的结果
        boolean result = false;
        //根据服务名字判断是否存在
        ActivityManager myManager=(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(30);
        for(int i = 0 ; i<runningService.size();i++)
        {
            if(runningService.get(i).service.getClassName().toString().equals(serviceName))
            {
                //找到符合的服务就返回真
                result = true;
            }
        }
        return result;
    }

    private void popSetWindow(){
        //创建view
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.view_set_inner, null);

        final EditText from_et=(EditText)view.findViewById(R.id.from_et);
        from_et.setText("A");
        AlertDialog.Builder ad =new AlertDialog.Builder(context);
        ad.setView(view);
        ad.setTitle("室内导航起点设置");
        selfdialog =ad.create();
        selfdialog.setButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //获取输入框的起点
                fromChar = from_et.getText().toString().charAt(0);
            }
        });
        selfdialog.setButton2("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                selfdialog.cancel();
            }
        });
        selfdialog.show();
    }

}
